//
//  ST_QuickMessageViewModel.swift
//  btvideo
//
//  Created by mac on 2021/9/7.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import Foundation
import RxSwift
import RxCocoa
import Alamofire

class ST_QuickMessageViewModel {
    
    /// 分类
    let categories: [QuickMessageCategory] = [.text, .voice]
    
    /// 选中的分类
    let selectedCategory = BehaviorRelay<QuickMessageCategory>(value: .text)
    
    /// 是否在编辑中
    let isEditing = BehaviorRelay<Bool>(value: false)
    
    /// 编辑状态文字
    let editStateText = BehaviorRelay<String>(value: "删除")
    
    /// 文字列表
    let textList = BehaviorRelay<[ST_QuickMessageModel]>(value: [])
    
    /// 语音列表
    let voiceList = BehaviorRelay<[ST_QuickMessageModel]>(value: [])
    
    /// 错误提示
    let errorSubject = PublishSubject<Error>()
    
    var disposeBag = DisposeBag()
    
    init() {
        
        selectedCategory
            .distinctUntilChanged()
            .subscribe(onNext: { [weak self] category in
                self?.fetchData(category: category)
            })
            .disposed(by: disposeBag)
        
        isEditing
            .map { $0 ? "取消" : "删除" }
            .bind(to: editStateText)
            .disposed(by: disposeBag)
    }
    
    /// 获取列表数据
    /// - Parameter type: 获取数据的类型
    /// - Returns: Single
    private func fetch_data_single(category: QuickMessageCategory) -> Single<[ST_QuickMessageModel]> {
        
        Single.create { single in
            JVrequest(PH.quickMessageListApi, parameters: ["type": category.rawValue]) { (json) in
                let models = json["data"].arrayValue.map({ ST_QuickMessageModel.deserialize(from: $0.dictionary) }).compactMap { $0 }
                single(.success(models))
            } failure: { (code, error) in
                single(.failure(ST_MyError.description(error)))
            }
            return Disposables.create()
        }

    }
    
    /// 获取列表数据
    /// - Parameter type: 获取数据的类型
    func fetchData(category: QuickMessageCategory) {
        fetch_data_single(category: category)
            .subscribe(onSuccess: { [weak self] models in
                switch category {
                case .text: self?.textList.accept(models)
                case .voice: self?.voiceList.accept(models)
                default: break
                }
            }, onFailure: { [weak self] error in
                self?.errorSubject.onNext(error)
            })
            .disposed(by: disposeBag)
    }
    
    /// 删除一条快捷搭讪信息
    /// - Parameter id: 数据ID
    /// - Returns: Single
    func deleteItem(_ id: Int) -> Single<Void> {
        Single.create { single in
            JVrequest(PH.deleteQuickMessageListApi, parameters: ["greet_id": id]) { json in
                single(.success(()))
            } failure: { (code, error) in
                single(.failure(ST_MyError.description(error)))
            }
            return Disposables.create()
        }
    }
    
    /// 缓存语音文件
    /// - Parameter urlString: 语音文件远程路径
    /// - Returns: 语音文件本地路径
    func cacheVoice(urlString: String) -> Single<String> {
        
        let path = quickMessageCacheURL.appendingPathComponent(urlString)
        
        return
            Single.create { single in
                AF.download(urlString, to: { (url, response) in
                    
                    return (path, [.removePreviousFile, .createIntermediateDirectories])
                })
                .response { response in
                    switch response.result {
                    case .success:
                        single(.success(path.path))
                    case .failure(let error):
                        single(.failure(error))
                    }
                }
                return Disposables.create()
            }
    }
}
